﻿using SelfHosting.Handlers.Compression;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace SelfHosting.Handlers
{
    /// <summary>
    /// Gesion de la décompression
    /// </summary>
    public class DecompressionHandler : HttpClientHandler
    {
        /// <summary>
        /// Obtient ou définit la collection des compresseurs
        /// </summary>
        public Collection<ICompressor> Compressors;

        /// <summary>
        /// Constructeur de la classe DecompressionHandler
        /// </summary>
        public DecompressionHandler()
        {
            Compressors = new Collection<ICompressor>();
            Compressors.Add(new GZipCompressor());
            Compressors.Add(new DeflateCompressor());
        }

        /// <summary>
        /// Réception d'une requête HTTP compressé
        /// </summary>
        /// <param name="request">requête</param>
        /// <param name="cancellationToken">objet permettant d'annuler l'opération</param>
        /// <returns>objet représentant l'opération asynchrone</returns>
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>((responseToCompleteTask) =>
                {
                HttpResponseMessage response = responseToCompleteTask.Result;
                if (request.Headers.AcceptEncoding != null)
                {
                    var encoding = request.Headers.AcceptEncoding.First();

                    var compressor = Compressors.FirstOrDefault(c => c.EncodingType.Equals(encoding.Value, StringComparison.InvariantCultureIgnoreCase));

                    if (compressor != null)
                    {
                        response.Content = new DecompressedContent(response.Content, compressor);
                    }
                }
                return response;
            });
        }
    }
}
